package red.stu.mc.mod.codeblock.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public final class FileTool {

	public static void main(String[] args) {
		String tmpDir = "C:\\Users\\ASUS\\AppData\\Local\\Temp\\codeBlockIDETemp\\test1.y";
		File testFile = tryCreateFile(tmpDir);
		String data = readToString(testFile, "UTF-8");
		System.out.println(data);
		writeToString(testFile, data + "Yihrmc File Test 中文测试.");
	}

	/**
	 * 尝试创建文件，如果文件存在就不创建
	 * @param fileName
	 * @return
	 */
	public static File tryCreateFile(String fileName) {
		File file = new File(fileName);
		try {
			if (!file.exists())
				file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

	public static String readToString(File file, String encoding) {
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		StringBuffer sf = new StringBuffer();
		try {
			FileInputStream in = new FileInputStream(file);
			while (in.read(filecontent) > 0) {
				sf.append(new String(filecontent, encoding));
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sf.toString();
	}

	public static void writeToString(File file, String data) {
		try {
			FileOutputStream fos = new FileOutputStream(file);
			try {
				fos.write(data.getBytes("UTF-8"));
			} catch (IOException e) {
				e.printStackTrace();
			}
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
